package com.csust.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csust.reggie.common.R;
import com.csust.reggie.domain.Category;
import com.csust.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yinweiguang
 * @date 2022-04-01 18:05
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;


    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize){

        log.info("page = {},pageSize = {}" ,page,pageSize);
        //构造分页构造器
        Page<Category> pageInfo = new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();

        //添加排序条件
        queryWrapper.orderByDesc(Category::getSort);

        //执行查询
        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     *  新增菜品
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category = {}",category.toString());
        boolean save = categoryService.save(category);
        if (save) {
            return R.success("添加成功");
        }else {
            return R.error("添加失败");
        }
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("获取的category是： {}",category.toString());
        boolean b = categoryService.updateById(category);
        if (b) {
            return R.success("更新成功");
        } else {
            return R.error("错误的菜品");
        }
    }

    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除Category的id是： {}",id);
        boolean b = categoryService.removeById(id);
        if (b) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        log.info("根据条件查询分类数据： {}",category.toString());
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        // 添加排序规则
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        return R.success(categoryService.list(queryWrapper));
    }


}
